package com.dotflat.training.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dotflat.util.excelUtil.StringUtils;
import com.matt.foundation.utils.HttpClientUtil;
import com.matt.service.SchedulerPlanService;
import com.tuo51.components.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
public class XETTokenService {


    @Value("${xiaoetong.appId}")
    private String appId;
    @Value("${xiaoetong.clientId}")
    private String clientId;
    @Value("${xiaoetong.secretKey}")
    private String secretKey;
    @Value("${xiaoetong.grantType}")
    private String grantType;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SchedulerPlanService schedulerPlanService;

    public String accessToken() {
        String key = "xet_access_token_" + appId;
        String accessToken = redisService.getValue(key);
        if (StringUtils.isNotEmpty(accessToken)){
            return accessToken;
        }

        schedulerPlanService.updateXetAccessToken();

        accessToken = redisService.getValue(key);

        if (accessToken == null){
            accessToken = "";
        }

        return accessToken;
    }

    public void clearAccessToken(){
        String key = "xet_access_token_" + appId;
        redisService.delKey(key);
    }

    public void updateAccessToken(){
        String url = "https://api.xiaoe-tech.com/token?app_id="+appId+"&client_id="+clientId+"&secret_key="+secretKey+"&grant_type="+grantType;
        String responseJson = null;
        try {
            responseJson = HttpClientUtil.sendGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSON.parseObject(responseJson);
        System.out.println("小鹅通ACCESS_TOKEN返回结果："+JSON.toJSON(json));
        Map map = (Map) json.get("data");
        if (map == null){
            return;
        }
        String accessToken = String.valueOf(map.get("access_token"));
        if (StringUtils.isBlank(accessToken)){
            return;
        }
        String key = "xet_access_token_" + appId;
        redisService.saveValue(key, accessToken);
    }

}
